package com.swh.zuul.filters;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.filters.FilterRegistry;
import com.netflix.zuul.monitoring.MonitoringHelper;

/**
 * 此类中的filterType会在启动后中加载
 * @author sangwenhao-桑文豪
 * @date 2016年12月31日 上午1:35:39
 */
@Component
public class MyCommonFilter implements CommandLineRunner{

	private static final Logger logger = LoggerFactory.getLogger(MyCommonFilter.class);

	@Override
	public void run(String... arg0) throws Exception {
		MonitoringHelper.initMocks();//启动监控
		gatewayFilter() ;
	}
	
	private void gatewayFilter(){
		FilterRegistry filterRegistry = FilterRegistry.instance();
		
		//请求中过滤
		filterRegistry.put("routingFilter", new ZuulFilter() {
			
			@Override
			public boolean shouldFilter() {
				logger.info(">>>>>>>>>>>>> 进入route >>> shouldFilter...");
				return true;
			}
			
			@Override
			public Object run() {
				logger.info(">>>>>>>>>>>>> 进入route >>> run...");
//				try {
					RequestContext requestContext = RequestContext.getCurrentContext();
					HttpServletRequest request = requestContext.getRequest();
					logger.info(">>>>>>>>>>>>>  进入route >>> run request:"+request);
//                    RequestContext.getCurrentContext().getResponse().sendRedirect("http://www.baidu.cm/");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                return null;
			}
			
			@Override
			public String filterType() {
				logger.info(">>>>>>>>>>>>> 进入route >>> filterType...");
				return "route";
			}
			
			@Override
			public int filterOrder() {
				logger.info(">>>>>>>>>>>>> 进入route >>> filterOrder...");
				return 10;
			}
		});
		
		//请求之后过滤
		filterRegistry.put("postFilter", new ZuulFilter() {
			
			@Override
			public boolean shouldFilter() {
				logger.info(">>>>>>>>>>>>> 进入post >>> shouldFilter...");
				return true ;
			}
			
			@SuppressWarnings("static-access")
			@Override
			public Object run() {
				logger.info(">>>>>>>>>>>>> 进入post >>> run...");
				RequestContext requestContext = RequestContext.getCurrentContext();
				HttpServletRequest request = requestContext.getRequest();
				requestContext.getRouteHost();
				logger.info(String.format("error>>>%s request to %s -RouteHost- %s", request.getMethod(), request.getRequestURL().toString(),requestContext.getRouteHost()));
//				logger.info(">>>>>>>>>>>>>>name:"+RequestContext.getCurrentContext().get("name").toString());
				if(requestContext.getCurrentContext().isEmpty()){
				   requestContext.setResponseStatusCode(HttpStatus.BAD_GATEWAY.value());
		           requestContext.setSendZuulResponse(false);
		           logger.info("post>>> 返回内容为空 " );
				}/*else if(StringUtils.isNotBlank(requestContext.getResponseBody())){
					logger.info("post>>> "+requestContext.getResponseBody());
				}else {
					return "post>>> "+requestContext.getResponseStatusCode();
				}*/
				return null;
			}
			
			@Override
			public String filterType() {
				logger.info(">>>>>>>>>>>>> 进入post >>> filterType...");
				return "post";
			}
			
			@Override
			public int filterOrder() {
				logger.info(">>>>>>>>>>>>> 进入post >>> filterOrder...");
				return 10;
			}
		});
		//路由转发时出错处理过程
		filterRegistry.put("error", new ZuulFilter() {
			
			@Override
			public boolean shouldFilter() {
				logger.info(">>>>>>>>>>>>> 进入error >>> shouldFilter...");
				return true;
			}
			
			@Override
			public Object run() {
				logger.info(">>>>>>>>>>>>> 进入error >>> run...");
				RequestContext requestContext = RequestContext.getCurrentContext();
				HttpServletRequest request = requestContext.getRequest();
//				logger.info(String.format("error>>>%s request to %s", request.getMethod(), request.getRequestURL().toString()));
				int status = requestContext.getResponseStatusCode();
				if(status == HttpStatus.UNAUTHORIZED.value()){
					logger.info("error >>> "+"非法请求") ;
				}else if(status == HttpStatus.BAD_GATEWAY.value()){
					logger.info("error >>> "+"路由失败");
				}else if(status == HttpStatus.REQUEST_TIMEOUT.value()){
					logger.info("error >>> "+"请求超时") ;
				}else if(status == HttpStatus.BAD_REQUEST.value()){
					logger.info("error >>> "+"错误的请求");
				}
				return null;
			}
			
			@Override
			public String filterType() {
				logger.info(">>>>>>>>>>>>> 进入error >>> filterType...");
				return "error";
			}
			
			@Override
			public int filterOrder() {
				logger.info(">>>>>>>>>>>>> 进入error >>> filterOrder...");
				return 10;
			}
		});
	}

}
